/**
 * 客户资源录入脚本支持
 */
var clientKey = ""; ;
var modifydata = null;
var date = "";
var time = "";
var region = "";
var modifyKey = "";
var studentKey = "";
var authorize = false;
var myself = true;

//页面载入初始化
$( "body" ).ready( function( e )
{
	try
	{
		if( typeof ( eval( "init" ) ) == "function" )
			eval( "init();" );
	}
	catch( e )
	{
	}

	// 键盘事件
	$( "body" ).bind( "keyup", bodyKeyupHandler );

	// 初始化
	button_bind();
	init_editors();

	// 初始化选择中心
	$( "#region" ).val( region );

	client_detailed( $( "#tbl_client" ), false );
	//client_detailed( $( "#tbl_student" ), false );
	client_detailed( $( "#tbl_reserve" ), false );
	client_detailed( $( "#tbl_reserve" ), false, "hide2" );
	client_detailed( $( "#tbl_reserve_log" ), false );

	// 绑定学员点击事件
	bind_st_click( true );
	init_table_sh_click( $( "#tbl_reserve_log" ) );
	init_table_sh_click( $( "#tbl_reserve" ) );

	// 修改数据设置
	if( modifydata && modifydata.key )
	{
		changeState( "modify" );
		setModifyData( modifydata );
		search_reserve_log( clientKey );
		client_detailed( $( "#tbl_reserve" ), true );

		//if( modifydata.state == 2 || !authorize || !myself )
		if( modifydata.state == 2 )
		{
			//$( "#statebx" ).hide();
			//$( "#btnSubmit" ).hide();
			$( "#remark" ).attr( "contenteditable", false );
		}
	}
} );

/**
 * 初始化以fields为样式名的标题栏具备隐藏和显示其它表格行的功能
 */
function init_table_sh_click( tbl )
{
	var th = tbl.find( "tr[class=fields] th" );

	th.css( "cursor", "pointer" );
	th.bind( "click", function()
	{
		var trs = $( this ).parent().parent().find( "tr[class!=fields]" );
		trs.eq( 0 ).css( "display" ) == "none" ? trs.show() : trs.hide();
	} );
}

//--------------------------------------------------------------------------
//
//	consultant_client.php
//
//--------------------------------------------------------------------------

var _editor = [];

function button_bind()
{
	change_tracking_button_state();

	/*$( "#btnSelect" ).bind( "click", function()
	{
		parent.clienter.setCallback( clientSelectedHandler );
		parent.clienter.reset();
		parent.clienter.open();
	} );*/

	$( "#btnSubmit" ).bind( "click", function()
	{
		submit_form();
	} );

	$( "#btn_detailed" ).click( function( e )
	{
		e.stopPropagation();

		var show = $( "#tbl_client" ).find( "tr[rel='hide']" ).eq( 0 ).visible();
		client_detailed( $( "#tbl_client" ), !show );
	} );

	$( "#btn_students" ).click( function( e )
	{
		e.stopPropagation();

		var show = $( "#tbl_student" ).find( "tr[rel='hide']" ).eq( 0 ).visible();
		client_detailed( $( "#tbl_student" ), !show );
	} );

	$( "#non" ).change( function()
	{
		var is_non = $( this ).prop( "checked" );
		client_detailed( $( "#tbl_reserve" ), is_non, "hide2" );

		if( !is_non )
		{
			$( "#tbl_student" ).show();
			bind_st_click( true );
		}
		else
		{
			$( "#tbl_student" ).hide();
			bind_st_click( false );
		}
	} );

	$( "#date" ).change( function()
	{
		date = $( this ).val();
		$( "#receptionlst ul" ).empty();
	} );

	$( "#time" ).change( function()
	{
		time = $( this ).val();
		$( "#receptionlst ul" ).empty();
	} );

	$( "#needtime" ).change( function()
	{
		$( "#receptionlst ul" ).empty();
	} );

	$( "#region" ).change( function()
	{
		region = $("#region").val();
		$( "#receptionlst ul" ).empty();
	} );

	$( "#btnSearchReception" ).click( function( e )
	{
		e.stopPropagation();
		search_reception();
	} );

	$( "#btnRestoryReception" ).click( function( e )
	{
		e.stopPropagation();
		restory_reception();
	} );

	// 未出现状态时，可以直接添加客户跟踪
	$( "#state" ).change( change_tracking_button_state );
}

function exec_tracking()
{
	if( empty( clientKey ) )
	{
		infopad.err( "请先指定目标客户，再添加跟踪情况。" );
		return;
	}
	
	var url = "consultant_client.htm?key=" + clientKey + "&state=9xsr8y47w1ov";
	var title = "添加“未出现”跟踪记录";
	var id = "consultant_client_tracking";

	parent.create_model( url, title, id, 9000 );
	parent.open_model( id );
}

function change_tracking_button_state()
{
	var state = $( "#state" ).val();

	if( state == 3 )
	{
		$( "#btnAddTracking" ).show();
		$( "#btnAddTracking" ).click();
	}
	else
	{
		$( "#btnAddTracking" ).hide();
	}
}

function init_editors()
{
	$( "div[contenteditable='true']" ).each( function()
	{
		_editor.push( $( this ).attr( "id" ) );
	} );
}

function client_detailed( tar, visible, rel )
{
	var r = "hide";

	if( !empty( rel ) )
		r = rel;

	if( visible )
		tar.find( "tr[rel='" + r + "']" ).show();
	else
		tar.find( "tr[rel='" + r + "']" ).hide();

	setTableRowBackColor( tar );
}

function bind_st_click( flag )
{
	if( flag )
	{
		$( "#studentlst ul li" ).click( function()
		{
			$( this ).toggleClass( "selected" );
		} );
	}
	else
	{
		$( "#studentlst ul li" ).unbind( "click" );
	}
}

//--------------------------------------------------------------------------
//
//	数据提交
//
//--------------------------------------------------------------------------

function clientSelectedHandler( data )
{
	if( typeof ( data ) == "undefined" )
		return;

	// 有效用户检测
	if( data.invalid == 1 || data.source == "cru0943rdrf2" || data.category == "510a4qf1i57p" )
	{
		infopad.err( "无效、未知、广告推销类型的客户不能进行预约。" );
		return;
	}

	setClientData( data );

	// 选择新客户时置空修改目标属性
	modifyKey = "";
	studentKey = "";

	if( clientKey != null )
	{
		request_student( clientKey );
		search_reserve_log( clientKey );
	}
}

function setClientData( data )
{
	// 客户资料
	if( typeof ( data ) == "object" && data.nickname )
	{
		clientKey = data.key;

		$( "#nickname" ).html(
				data.nickname
						+ ( data.invalid == 1 ? "<em class='caption'>（无效客户）</em>"
								: "<em class='valid'>（有效客户）</em>" ) );
		$( "#category" ).html( shtml( data.categoryns ) );
		$( "#source" ).html( shtml( data.sourcens ) );
		$( "#keyword" ).html( shtml( data.keyword ) );
		$( "#address" ).html( data.province + " " + data.city + " " + data.address );
		$( "#phone" ).html( shtml( data.phone ) );
		$( "#email" ).html( shtml( data.email ) );
		$( "#qq" ).html( shtml( data.qq ) );
		$( "#ip" ).html( shtml( data.ip ) );
		$( "#desc" ).html( shtml( data.desc ) );
	}
	else
	{
		clientKey = null;

		$( "#nickname" ).html( "&nbsp;" );
		$( "#category" ).html( "&nbsp;" );
		$( "#source" ).html( "&nbsp;" );
		$( "#address" ).html( "&nbsp;" );
		$( "#keyword" ).html( "&nbsp;" );
		$( "#phone" ).html( "&nbsp;" );
		$( "#email" ).html( "&nbsp;" );
		$( "#qq" ).html( "&nbsp;" );
		$( "#ip" ).html( "&nbsp;" );
		$( "#desc" ).html( "&nbsp;" );
	}
}

function shtml( val )
{
	if( empty( val ) )
		return "<em class='caption'>未填写</em>";
	else if( val == '--' )
		return "<em class='caption'>禁止查看</em>";
	return val;
}
//学生数据
/*function request_student( key )
{
	submitter.post( "student_search.php", {
		key: key
	}, function( d )
	{
		if( d.err == 0 )
		{
			$( "#studentlst ul" ).empty();

			var size = parseInt( d[ 'size' ] );
			for( var i = 0; i < size; i++ )
			{
				var v = d[ i ];
				insert_student( v );
			}

			// 重新绑定选定事件
			if( getState() == "add" )
				bind_st_click( true );
		}
		else
		{
			infopad.err( d.msg );
		}
	}, "json" );
}*/

//操作人
/*function search_reserve_log( clientKey )
{
	submitter.post( "client_reserve_log_search.php", {
		key: clientKey
	}, function( d )
	{
		if( d.err == 0 )
		{
			var size = parseInt( d[ 'size' ] );
			size > 0 && $( "#loglist ul" ).empty();

			for( var i = 0; i < size; i++ )
			{
				insert_reserve_log( d[ i ] );
			}
		}
		else
		{
			infopad.err( d.msg );
		}
	}, "json" );
}

function insert_reserve_log( d )
{
	var h = "<li class=\"rect\">";
	h += "<span><b>操作人：</b><label class=\"stress\">" + d.modifyer + "</label></span>";
	h += "<span style='padding-left:20px;'><b>操作时间：</b>" + d.date + "</span>";
	h += "<p class=\"line\"></p>";
	h += "<p><b>状态：</b><span class='unit hand " + state_style( d.state ) + "'>" + d.statens + "</span></p>";
	h += "<p><b>类型：</b>" + d.type + "</p>";
	h += "<p>" + d.remark + "</p>";
	h += "</li>";

	$( "#loglist ul" ).append( h );
}*/

function state_style( s )
{
	switch( parseInt( s ) ) {
		case 1:
			return 'confirmed';
		case 2:
			return 'completed';
		case 3:
			return 'expired';
		default:
			return '';
	}
}

function search_reception()
{
	var date = $( "#date" ).val();
	var time = $( "#time" ).val();
	var province = $( "#province" ).val();
	var city = $( "#city" ).val();
	var needtime = $( "#needtime" ).val();
	var region = $("#region").val();
		modifyKey = $("#keynames").val();
	submitter.post( contextPath+"/index/consultant_reserve_user_search.json", {
		key: modifyKey,
		date: date,
		time: time,
		province: province,
		city: city,
		needtime: needtime,
		region: region
	}, function(date)
	{
		var list = date.stuList;
			if( list.length > 0 ){
				$( "#receptionlst ul" ).empty();

				for( var i = 0; i <list.length; i++ )
				{
					var v = list[ i ];
					insert_reception_user( v );
				}

				// 重新绑定选定事件
				$( "#receptionlst ul li" ).click( function()
				{
					$( this ).parent().find( "li" ).each( function()
					{
						$( this ).removeClass( "selected" );
					} );
					$( this ).toggleClass( "selected" );
				} );
			}else{
				$( "#receptionlst ul" ).empty();
				infopad.err( "当前时间点，没有空闲接待老师！请调整预约时间点或者持续时间。" );
			}
		
		/*if( d.err == 0 )
		{
			var size = parseInt( d[ 'size' ] );
			if( size > 0 )
			{
				$( "#receptionlst ul" ).empty();

				for( var i = 0; i < size; i++ )
				{
					var v = d[ i ];
					insert_reception_user( v );
				}

				// 重新绑定选定事件
				$( "#receptionlst ul li" ).click( function()
				{
					$( this ).parent().find( "li" ).each( function()
					{
						$( this ).removeClass( "selected" );
					} );
					$( this ).toggleClass( "selected" );
				} );
			}
			else
			{
				$( "#receptionlst ul" ).empty();
				infopad.err( "当前时间点，没有空闲接待老师！请调整预约时间点或者持续时间。" );
			}
		}
		else
		{
			//infopad.err( d.msg );
		}*/
	}, "json" );
}

function restory_reception()
{
	// 还原数据设置
	if( modifydata && modifydata.key )
	{
		var d = modifydata;
		date = d.date;
		time = d.time;
		region = d.region;
		reception_u = d.reception_u;

		$( "#date" ).val( date );
		$( "#time" ).val( time );

		// 直接选定已经设置好的时间，随意更改，等提交时，再检测这个时间段内该咨询师是否有别的接待安排
		//$( "#needtime" ).val( d.needtime );

		// 设置当前接待人
		$( "#receptionlst ul" ).empty();
		insert_reception_user( {
			username: d.ur_username,
			nickname: d.receptionor,
			jobns: d.jobns
		} );
		$( "#receptionlst ul" ).find( "li#" + d.ur_username ).addClass( "selected" );
	}
}

function insert_reception_user( d )
{
	var h = "<li id=\"" + d.username + "\" class=\"unit\">";
	h += "<label class=\"stress\">" + d.nickname + "</label>";
	h += "，" + d.jobns;
	h += "</li>";

	$( "#receptionlst ul" ).append( h );
}

/**
 * 根据数据参数添加一条学员数据
 * 
 * @param d 数组
 */
function insert_student( d )
{
	var h = "<li rel=\"" + d.key + "\">";

	h += "<p class='title'><span>" + d.nickname + "</span></p>";
	h += "<p><b>性别</b><span>" + d.sex + "</span></p>";
	h += "<p><b>年龄</b><span>" + d.age + " 岁</span></p>";
	h += "<p><b>生日</b><span>" + ( empty( d.birthday ) ? "<em class='caption'>未填写</em>" : d.birthday )
			+ "</span></p>";
	h += "<p><b>学校</b><span>" + ( d.school == null ? "<em class='caption'>未填写</em>" : d.school )
			+ "</span></p>";
	h += "<p><b>学员特征</b></p>";
	h += "<div class=\"content\">" + d.feature + "</div>";
	h += "</li>";

	$( "#studentlst ul" ).append( h );

	// 根据数据选定已经保存的选择
	if( studentKey.indexOf( d.key ) != -1 )
		$( "#studentlst ul li:last" ).attr( "class", "selected" );
}

function empty_student()
{
	$( "#studentlst ul" ).empty();
	$( "#studentlst ul" ).append( "<li>暂无学员资料，不能进行预约。</li>" );
}


function submit_form(){

	var data = {};
	// 修改记录时需要传递 key，否则当新预约处理
	var key = $("#keynames").val();
	data.keyname = key;
	// 客户key
	data.client = $("#nickname").attr('name');
	if( empty( data.client ) )
	{
		alert( "未指定预约目标客户。" );
		return;
	}
	// 检测是否为非测评类型
	data.non = $( "#non" ).prop( "checked" ) ? 1 : 0;
	data.notice = $( "#notice" ).val();
	data.username = $("#user_nickname").attr('name');
	// 待测评的学员key，可能是多个
	var ks = [];
	$( "#studentlst ul li.selected" ).each( function()
	{
		ks.push( $( this ).attr( "rel" ) );
	} );
	data.student = ks.join( "," );
	
	if( empty( data.student ) && data.non == 0 )
	{
		alert("需要至少选择一位待测评的学员。");
		return;
	}
	//首次登记时也能保存非测评原因
	data.yuanyin = $( "#yuanyin" ).val();
	var states = [];
  	$( "#statelist2 input:checked" ).each( function(){
		var val = $( this ).attr( "value" );
		states.push( val );
	} );
	data.states = states.join( "," );
	// 预约数据
	data.date = $( "#date" ).val();
	data.time = $( "#time" ).val();
	data.region =$("#region").val();
	data.state = $( "#state" ).val();
	data.sms = $( "#sms" ).prop( "checked" ) ? 1 : 0;
	data.needtime = $( "#needtime" ).val();
	data.remark =  $( "#remarks" ).html();
	var datetime = data.date+" "+data.time;
	
	// 接待老师
	data.reception_u = $( "#receptionlst ul" ).find( "li.selected" ).attr( 'id' );
	
	if(empty( data.reception_u ) && data.reception_u == null ){
		alert("请选择一名接待老师！");
		return false;
	}
	var a = window.parent.$('.model_window').attr("id");
	
	
	submitter.post(contextPath+"/index/updatereserve.json", data, function( d )
	{
		alert("修改成功");
		parent.close_model(a);
	}, "json" );
}

function changeState( mode )
{
	if( mode == "modify" )
	{
		$( "#btnSelectBox" ).hide();
	}
	else
	{
		$( "#btnSelectBox" ).show();
	}
}

function getState()
{
	return $( "#btnSelectBox" ).visible() ? "add" : "modify";
}

function setModifyData( d )
{
	setClientData( d );

	// clientKey 放在 setClientData 之后，覆盖方法内赋值的内容
	modifyKey = d.key;
	clientKey = d.client;
	studentKey = d.student;
	date = d.date;
	time = d.time;
	region = d.region;
	reception_u = d.reception_u;

	// 显示还原当前咨询师按钮
	$( "#btnRestoryReception" ).show();

	// 设置当前接待人
	$( "#receptionlst ul" ).empty();
	insert_reception_user( {
		username: d.ur_username,
		nickname: d.receptionor,
		jobns: d.jobns
	} );
	$( "#receptionlst ul" ).find( "li#" + d.ur_username ).addClass( "selected" );

	if( clientKey != null )
		request_student( clientKey );

	$( "#date" ).val( date );
	$( "#time" ).val( time );
	$( "#remark" ).html( d.remark );

	$( "#sms" ).prop( "checked", d.sms == 1 );

	//	if( d.state == 2 || !authorize || !myself )
	//		$( "#smsbx" ).html( "<span class=\"stress unit hand\">" + ( d.sms == 1 ? "已" : "未" ) + "发送短信</span>" );

	// 测评类型，自由更改
	$( "#non" ).prop( "checked", d.non == 1 );

	if( d.non == 1 )
	{
		client_detailed( $( "#tbl_student" ), false );
		client_detailed( $( "#tbl_reserve" ), true, "hide2" );
		$( "#tbl_student" ).hide();

		$( "#notice" ).val( d.notice );
	}

	$( "#region" ).val( region );

	// 直接选定已经设置好的时间，随意更改，等提交时，再检测这个时间段内该咨询师是否有别的接待安排
	//$( "#needtime" ).val( d.needtime );
}

//--------------------------------------------------------------------------
//
//	methods
//
//--------------------------------------------------------------------------

function bodyKeyupHandler( e )
{
	if( e.ctrlKey && e.which == 13 )
	{
		submit_form();
	}
	else if( e.ctrlKey && e.shiftKey && e.which == 70 )// ctrl+shift+f
	{
		var edt = $( document.activeElement );
		var id = edt.attr( "id" );

		if( _editor.indexOf( id ) > -1 )
		{
			edt.html( htmlfilter( edt.html() ) );
		}
	}
}
